package com.lenovo.smarttraffic.ui.fragment;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lenovo.smarttraffic.Constant;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.api.VolleyCallBack;
import com.lenovo.smarttraffic.bean.GsonBean.AnnouncementBean;
import com.lenovo.smarttraffic.bean.GsonBean.NewsInfoBean;
import com.lenovo.smarttraffic.bean.GsonBean.TourSpotBean;
import com.lenovo.smarttraffic.bean.TrafficNewsBean;
import com.lenovo.smarttraffic.ui.activity.NetWorkActivity;
import com.lenovo.smarttraffic.ui.activity.TrafficDetailActivity;
import com.lenovo.smarttraffic.ui.adapter.MyInfoRecyclerViewAdapter;
import com.lenovo.smarttraffic.util.VolleyUtil;

import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Locale;


/**
 *
 */
public class FirstFragment extends BaseFragment {

    private RecyclerView mTrafficInfoRecycler;
    private SwipeRefreshLayout mMSwipeLayout;
    private MyInfoRecyclerViewAdapter myInfoRecyclerViewAdapter;
    private List<TrafficNewsBean> mlist;
    private static final String TAG = "FirstFragment";
    private SimpleDateFormat simpleDateFormat;
    private String category;
    private static final String FRAGMENT_CATEGORY = "com.lenovo.smarttraffic.ui.fragment.FirstFragment.bundle.fragmentCategory";

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        category = getArguments().getString(FRAGMENT_CATEGORY);//分类
        mlist = new ArrayList<>();
        simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());

    }

    @Override
    protected View getSuccessView() {
        View convertView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_traffic_info, null);
        initRecycler(convertView);
        mMSwipeLayout = convertView.findViewById(R.id.mSwipeLayout);
        mMSwipeLayout.setEnabled(false);
        return convertView;
    }

    private void refreshUI() {
        mMSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mMSwipeLayout.setRefreshing(false);
                if (myInfoRecyclerViewAdapter.getItemCount() == mlist.size()) {
                    showToast("内容加载完成，没有更多内容");
                } else {
                    ArrayList<TrafficNewsBean> trafficNewsBeans = new ArrayList<>();
                    if (myInfoRecyclerViewAdapter.getItemCount() + 1 == mlist.size()) {
                        trafficNewsBeans.addAll(mlist);
                    } else {
                        for (int i = 0; i < myInfoRecyclerViewAdapter.getItemCount() + 2; i++) {
                            trafficNewsBeans.add(mlist.get(i));
                        }
                    }
                    //刷新数据
                    myInfoRecyclerViewAdapter.setMlist(trafficNewsBeans);
                    showToast("已为您增加一组数据");
                }
            }
        });
    }

    private void initRecycler(View convertView) {
        mTrafficInfoRecycler = convertView.findViewById(R.id.traffic_info_recycler);

        mTrafficInfoRecycler.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        ArrayList<TrafficNewsBean> initList = new ArrayList<>();
        //设置适配器
        myInfoRecyclerViewAdapter = new MyInfoRecyclerViewAdapter(getActivity(), initList);
        mTrafficInfoRecycler.setAdapter(myInfoRecyclerViewAdapter);
        mTrafficInfoRecycler.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
                outRect.top = 16;
            }
        });
        showRecyclerDetails();
    }

    private void showToast(String content) {
        Toast toast = new Toast(getActivity());
        View inflate = LayoutInflater.from(getActivity()).inflate(R.layout.mytoast, null, false);
        TextView viewById = (TextView) inflate.findViewById(R.id.toast_text);
        viewById.setText(content);
        toast.setView(inflate);
        toast.setGravity(Gravity.TOP, 0, 250);
        toast.show();
    }


    @Override
    protected Object requestData() {
        getNews();
        return "loading";
    }

    @Override
    public void onClick(View view) {

    }

    /**
     * 类似于 Activity的 onNewIntent()
     */
    @Override
    public void onNewBundle(Bundle args) {
        super.onNewBundle(args);
        Toast.makeText(_mActivity, args.getString("from"), Toast.LENGTH_SHORT).show();
    }


    private void showRecyclerDetails() {
        myInfoRecyclerViewAdapter.setOnItemClickListener(pos -> {
            Intent intent = new Intent(getActivity(), TrafficDetailActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable(Constant.TRAFFIC_ITEM_DETAIL, mlist.get(pos));
            bundle.putString(Constant.TRAFFIC_FRAGMENT_CATEGORY, category);
            intent.putExtra(Constant.TRAFFIC_ITEM_INTENT_DETAIL, bundle);
            startActivity(intent);
        });
    }

    private void getSpot() {
        VolleyUtil.post("GetSpotInfo.do", new JSONObject(), new VolleyCallBack() {
            @Override
            public void onSucceess(JSONObject jsonObject, String response) {
                TourSpotBean tourSpotBean = new Gson().fromJson(response, TourSpotBean.class);
                if (tourSpotBean.getRESULT().equals("S")) {
                    for (TourSpotBean.ROWSDETAILBean item :
                            tourSpotBean.getROWS_DETAIL()) {
                        mlist.add(new TrafficNewsBean(Constant.TRAFFIC_ITEM_SPOT, simpleDateFormat.format(new Date()), item.getInfo(),
                                new StringBuilder().append("http://").append(NetWorkActivity.getIP(getActivity())).append(":").
                                        append(Constant.PORT).append(Constant.IMAGE_CONTENT).append(item.getImg()).toString(), item.getName()
                        ));
                    }
                    Collections.sort(mlist, new Comparator<TrafficNewsBean>() {
                        @Override
                        public int compare(TrafficNewsBean o1, TrafficNewsBean o2) {
                            try {
                                Date parse1 = simpleDateFormat.parse(o1.getCreateTime());
                                Date parse2 = simpleDateFormat.parse(o2.getCreateTime());
                                if (parse1.before(parse2)) {
                                    return 1;
                                } else {
                                    return -1;
                                }
                            } catch (ParseException e) {
                                e.printStackTrace();
                                return 0;
                            }
                        }
                    });
                    refreshPage(mlist);
                    myInfoRecyclerViewAdapter.setMlist(mlist.subList(0, 2));
                    //ToDO
                    mMSwipeLayout.setEnabled(true);
                    refreshUI();
                }
            }

            @Override
            public void onFailure(String onError) {
                refreshPage(null);
            }
        });


    }

    private void getAnouncement() {
        VolleyUtil.post("GetMotorwayAnnouncement.do", new JSONObject(), new VolleyCallBack() {
            @Override
            public void onSucceess(JSONObject jsonObject, String response) {
                AnnouncementBean announcementBean = new Gson().fromJson(response, AnnouncementBean.class);
                if (announcementBean.getRESULT().equals("S")) {
                    for (AnnouncementBean.ROWSDETAILBean item :
                            announcementBean.getROWS_DETAIL()) {
                        mlist.add(new TrafficNewsBean(Constant.TRAFFIC_ITEM_NEWS_ANNCEMENT,
                                item.getCreateTime(), item.getContent()
                                , item.getTitle()));
                    }
                    getSpot();
                }
            }

            @Override
            public void onFailure(String onError) {
                refreshPage(null);

            }
        });
    }

    private void getNews() {
        VolleyUtil.post("GetNewsInfo.do", new JSONObject(), new VolleyCallBack() {
            @Override
            public void onSucceess(JSONObject jsonObject, String response) {
                NewsInfoBean newsInfoBean = new Gson().fromJson(response, NewsInfoBean.class);
                if (newsInfoBean.getRESULT().equals("S")) {
                    for (NewsInfoBean.ROWSDETAILBean item :
                            newsInfoBean.getROWS_DETAIL()) {
                        mlist.add(new TrafficNewsBean(Constant.TRAFFIC_ITEM_NEWS_ANNCEMENT,
                                item.getCreatetime(), item.getContent()
                                , item.getTitle()));
                    }
                    getAnouncement();
                }

            }

            @Override
            public void onFailure(String onError) {
                refreshPage(null);
            }
        });
    }


    public static Fragment newInstance(String fragmentCataGory) {
        Bundle bundle = new Bundle();
        bundle.putString(FRAGMENT_CATEGORY, fragmentCataGory);
        FirstFragment firstFragment = new FirstFragment();
        firstFragment.setArguments(bundle);
        return firstFragment;
    }

}
